package wsz.sqlSession;

import wsz.pojo.Configuration;
import wsz.pojo.MappedStatement;

import java.util.*;

/**
 * 默认实现类
 * @author wsz
 * @date 2021/10/1 1:17
 **/
public class DefaultSqlSession implements SqlSession{

    private Configuration configuration;
    private DefaultExecutor executor;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
        this.executor = new DefaultExecutor();
    }

    /**
     * 使用反射获取
     * @param mapperClass
     * @param <T>
     * @return
     */
    @Override
    public <T> T getMapper(Class<?> mapperClass) {
        return (T) configuration.getMapper(mapperClass, this);
    }

    @Override
    public int insert(String statement, Object... params) {
        return update(statement, params);
    }

    @Override
    public int update(String statement, Object... params) {
        MappedStatement mappedStatement = configuration.getStatementMap().get(statement);
        try {
            return executor.update(configuration, mappedStatement, params);
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new RuntimeException("update error");
    }

    @Override
    public int delete(String statement, Object... params) {
        MappedStatement mappedStatement = configuration.getStatementMap().get(statement);
        try {
            return executor.delete(configuration, mappedStatement, params);
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new RuntimeException("delete error");
    }

    @Override
    public <E> List<E> selectList(String statementId, Object... params){
        MappedStatement statement = configuration.getStatementMap().get(statementId);
        try {
            return executor.query(configuration, statement, params);
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new RuntimeException("selectList query failed");
    }

    @Override
    public <T> T selectOne(String statementId, Object... params) {
        List<Object> objects = selectList(statementId, params);
        if (objects.size() == 1) {
            return (T) objects.get(0);
        }
        throw new RuntimeException("dataResult is empty or more than 2");
    }

    @Override
    public <K, V> Map<K, V> selectMap(String statement, Object... params) {
        List<? extends V> list = new ArrayList<>();
        try {
            list = this.selectList(statement, params);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 使用map封装
        Map<K, V> result = new HashMap<>();

        Iterator var8 = list.iterator();
        while(var8.hasNext()) {
            K k = (K) "1";
            V v = (V) var8.next();
            result.put(k, v);
        }

        return result;
    }

    @Override
    public Configuration getConfiguration() {
        return configuration;
    }


}
